import React, {Component} from 'react';
import {Platform, View, Text, ViewPropTypes, StatusBar, StyleSheet} from 'react-native';
import {PropTypes} from 'prop-types';

const NAV_BAR_HEIGHT_IOS = 44;  // 导航栏在ios中的高度
const NAV_BAR_HEIGHT_ANDROID = 50;   // 导航栏在android中的高度
const STATUS_BAR_HEIGHT = 20;  // 状态栏的高度

// 设置状态栏属性
const StatusBarShape = {
  barStyle: PropTypes.oneOf(['light-content', 'default',]),
  hidden: PropTypes.bool,
  backgroundColor: PropTypes.string
};

// 自定义顶部导航栏
class NavigationBar extends Component {
  // 类型检查
  static propTypes = {
    style: ViewPropTypes.style,
    title: PropTypes.string,
    titleView: PropTypes.element,
    titleLayoutStyle: ViewPropTypes.style,
    hide: PropTypes.bool,
    statusBar: PropTypes.shape(StatusBarShape),
    rightButton: PropTypes.element,
    leftButton: PropTypes.element,
  };

  // 设置默认属性
  static defaultProps = {
    statusBar: {
      barStyle:'light-content',
      hidden: false,
    },
  };

  render() {
    // 顶部状态栏
    let statusBar = !this.props.statusBar.hidden ?
      <View style={styles.statusBar}>
        <StatusBar {...this.props.statusBar}/>
      </View> : null;

    //  中间的title
    let titleView = this.props.titleView ? this.props.titleView :
      <Text ellipsizeMode='head' numberOfLines={1} style={styles.title}>
        {this.props.title}
      </Text>;

    // 导航栏
    let content = this.props.hide ? null :
      <View style={styles.navBar}>
        {/* 左边返回按钮 */}
        {this.getButtonElement(this.props.leftButton)}
        {/* 中间的title */}
        <View style={[styles.navBarTitleContainer, this.props.titleLayoutStyle]}>
          {titleView}
        </View>
        {/* 右边的按钮 */}
        {this.getButtonElement(this.props.rightButton)}
      </View>;

    return <View style={[styles.container, this.props.style]}>
      {statusBar}
      {content}
    </View>
  }

  getButtonElement = (data) => {
    return <View style={styles.navBarButton}>
      {data ? data : null}
    </View>
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor:'#2196f3',
  },
  statusBar: {
    height: Platform.OS === 'ios' ? STATUS_BAR_HEIGHT : 0
  },
  title: {
    fontSize:20,
    color:'#fff',
  },
  navBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: Platform.OS === 'ios' ? NAV_BAR_HEIGHT_IOS : NAV_BAR_HEIGHT_ANDROID
  },
  navBarTitleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    position:'absolute',
    left: 40,
    right: 40,
    top:0,
    bottom:0
  },
  navBarButton: {
    alignItems: 'center'
  }
});

export default NavigationBar;